package tech.eyao.hs60x.utils;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import tech.eyao.hs60x.common.CommonConstants;

public class AesEcryptUtils {
	
	// 自定义随机源
	public static final String RANDOM_KEY = "1@#88447AS23&^%$#$";
	
	
	/**
	 * 加密
	 * @param encodeRules
	 * @param content
	 * @return
	 */
	public static String encode(String encodeRules,String content){
        try {
            KeyGenerator keygen=KeyGenerator.getInstance(CommonConstants.ECRYPT_TYPE);
            // 初始化密钥生成器  生成128位的随机源
            SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(encodeRules.getBytes());
            keygen.init(128, random);
            // 对称密钥数组
            byte [] raw=keygen.generateKey().getEncoded();
            // 生成AES密钥
            SecretKey key=new SecretKeySpec(raw, CommonConstants.ECRYPT_TYPE);
            // AES密码器
            Cipher cipher=Cipher.getInstance(CommonConstants.ECRYPT_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            // 字符编码
            byte [] byte_encode=content.getBytes("utf-8");
            // 将数据加密
            return new String(Base64Utils.encode(cipher.doFinal(byte_encode)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;         
    }
	
	/**
	 * 解密
	 * @param encodeRules
	 * @param content
	 * @return
	 */
	public static String decode(String encodeRules,String content){
        try {
            KeyGenerator keygen=KeyGenerator.getInstance(CommonConstants.ECRYPT_TYPE);
            SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(encodeRules.getBytes());
            keygen.init(128, random);
            byte [] raw=keygen.generateKey().getEncoded();
            SecretKey key=new SecretKeySpec(raw, CommonConstants.ECRYPT_TYPE);
            Cipher cipher=Cipher.getInstance(CommonConstants.ECRYPT_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte [] byte_content= Base64Utils.decode(content.getBytes());
            byte [] byte_decode=cipher.doFinal(byte_content);
            return new String(byte_decode,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;         
    }
}
